package com.pzl.handlerthread;

import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;

import java.util.Random;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    private HandlerThread mHandlerThread;
    private Handler mWorkHandler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    }

    @Override
    protected void onResume() {
        super.onResume();
        mHandlerThread = new HandlerThread("threadName");
        mHandlerThread.start();
        mWorkHandler = new Handler(mHandlerThread.getLooper()) {
            @Override
            public void handleMessage(Message msg) {//it worked in workThread
                super.handleMessage(msg);
                if (msg.what == 1) {
                    for (int i = 0; i < 10; i++) {
                        Log.i(TAG, "" + (char) (msg.obj));
                        try {
                            Thread.sleep(300);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        };
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mHandlerThread.quit();
    }

    public void click(View v) {
        Message msg = mWorkHandler.obtainMessage(1);
        msg.obj = (char) (65 + new Random().nextInt(10));
        mWorkHandler.sendMessage(msg);
    }

}
